package com.nbsaas.boot.sql;

import net.sf.jsqlparser.expression.*;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;

public class SqlConditionAppender2 {

    public static String addCondition(String sql, Expression newCondition) throws Exception {
        Statement stmt = CCJSqlParserUtil.parse(sql);
        if (stmt instanceof Select) {
            PlainSelect plainSelect = (PlainSelect) ((Select) stmt).getSelectBody();

            Expression oldWhere = plainSelect.getWhere();
            if (oldWhere == null) {
                // 没有 WHERE，直接设置
                plainSelect.setWhere(newCondition);
            } else {
                // 已有 WHERE，追加 AND
                AndExpression andExpr = new AndExpression(oldWhere, newCondition);
                plainSelect.setWhere(andExpr);
            }
            return plainSelect.toString();
        }
        return sql;
    }

    public static void main(String[] args) throws Exception {
        String sql = "SELECT id, name FROM users";

        // 条件1：age > 20
        Expression condition1 = CCJSqlParserUtil.parseCondExpression("age > 20");
        sql = addCondition(sql, condition1);
        System.out.println(sql);  // SELECT id, name FROM users WHERE age > 20

        // 条件2：status = 'active'
        Expression condition2 = CCJSqlParserUtil.parseCondExpression("status = 'active'");
        sql = addCondition(sql, condition2);
        System.out.println(sql);  // SELECT id, name FROM users WHERE age > 20 AND status = 'active'
    }
}
